package me.out1kiss.www.controller;

import com.google.zxing.BarcodeFormat;
import me.out1kiss.www.response.TwodimensioncodeResponse;
import me.out1kiss.www.tools.Generate2Dimension;
import me.out1kiss.www.util.MyUtil;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class ToolsController {

    @GetMapping("/twodimensioncode")
    public ResponseEntity<TwodimensioncodeResponse> twodimensioncode(String key) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(Generate2Dimension.generate(key, 300, 300, BarcodeFormat.QR_CODE), "png", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(new TwodimensioncodeResponse(Base64.encodeBase64String(out.toByteArray())), HttpStatus.OK);
    }

    @Value("${minio.mc.file.dir}")
    private String fileDir;

    @GetMapping("/searchFileKey")
    public ResponseEntity<Map<String, List<String>>> searchFileKey(String key) {
        Map<String, List<String>> map = new HashMap<>();
        key = key.trim();
        List<String> list = MyUtil.getData(fileDir);
        String finalKey = key;
        String s1 = MyUtil.enRegex(key);
        List<String> response = new ArrayList<>();
        List<String> data1 = list.parallelStream().filter(s -> Arrays.stream(s.split(",")).anyMatch(ss -> ss.contains(finalKey)))
                .collect(Collectors.toList());
//        List<String> data2 = list.parallelStream()
//                .filter(s -> !data1.contains(s))
//                .filter(s -> Arrays.stream(s.split(",")).anyMatch(ss -> Pattern.compile(s1).matcher(ss).find()))
//                .collect(Collectors.toList());
//        List<String> data3 = list.parallelStream()
//                .filter(s -> !data1.contains(s))
//                .filter(s -> !data2.contains(s))
//                .filter(s -> Pattern.compile(s1).matcher(s).find())
//                .collect(Collectors.toList());
        response.addAll(data1);
//        response.addAll(data2);
//        response.addAll(data3);
        map.put("key", response);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }


    @GetMapping("/searchFileList")
    public ResponseEntity<Map<String, Object>> searchFileList(String key) throws IOException, InterruptedException {
        return getListResponseEntity(key, 1);
    }

    /**
     * minio.mc.pwd=/opt/minio_data/mc
     * minio.mc.tmp.dir=test
     * minio.mc.url=http://192.168.31.88:9000
     * minio.mc.username=admin
     * minio.mc.password=1qaz2wsx
     * minio.mc.data.dir=test/private/
     */
    @Value("${minio.mc.pwd}")
    private String mcPwd;
    @Value("${minio.mc.tmp.dir}")
    private String tmpDir;
    @Value("${minio.mc.url}")
    private String mcUrl;
    @Value("${minio.mc.username}")
    private String mcUsername;
    @Value("${minio.mc.password}")
    private String mcPassword;
    @Value("${minio.mc.data.dir}")
    private String mcDataDir;
    @Value("${minio.mc.show.url}")
    private String showUrl;

    private static final Logger LOGGER = LoggerFactory.getLogger(ToolsController.class);

    public static final List<String> allFile = new ArrayList<>();

    private ResponseEntity<Map<String, Object>> getListResponseEntity(String key, int count) throws IOException, InterruptedException {
        Map<String, Object> map = new HashMap<>();
        List<String> list = new ArrayList<>(getList(key));
        if (list.isEmpty()) {
            Map<String, Object> error = Map.of("error", List.of("没有匹配的结果"));
            return ResponseEntity.ok(error);
        }
        map.put("data", list);
        map.put("showUrl", showUrl);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    private List<String> getList(String key) throws IOException, InterruptedException {
        if (allFile.isEmpty()) {
            LOGGER.info("start getlist");
            allFile.addAll(getall());
            LOGGER.info("end getlist");
        }
        return allFile.stream().filter(l -> l.contains(key)).collect(Collectors.toList());
    }

    private List<String> getall() throws IOException, InterruptedException {
        InputStream in = new FileInputStream("/mnt/22ccb5ac-c3ba-4ad5-a7ec-fdc601ccc258/app/path.text");
        BufferedReader pBufferedReader = new BufferedReader(new InputStreamReader(in));
        List<String> list = pBufferedReader.lines().collect(Collectors.toList());
        try {
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
